<template>
  <input :accept="acceptType" ref="fileRef" type="file" style="display: none;" @change="beforeUpload" :multiple="props.multiple" :capture="props.capture || undefined" />

  <div class="list-btn" @click="openFile" v-if="!isDisable">
    <div class="btn">
      <div class="icon">
        <img :src="icon" alt="">
      </div>
      <div class="text">上传文件</div>
    </div>
    <div class="tip" v-if="tip">({{tip}})</div>
  </div>
  <!-- 列表上传 -->
  <div class="list-warpper">
    <div class="upload-list">
      <div class="item" v-for="(f, idx) in file.list">
        <div class="icon">
          <img :src="setIcon(f)" alt="">
        </div>
        <div style="flex: 1">
          <div class="name">{{ f.name }}</div>
          <div class="size-box" style="display: flex;justify-content: space-between;">
            <div class="size">
              {{ setFileSize(f.fileSize) }}
            </div>
			<div class="btns">
				<div class="btns-item" @click="handDown(f)">
					<div class="btn-icon">
					  <van-icon color="rgb(144,147,153)" name="down" />
					</div>
					<span>下载</span>
				</div>
				  <div class="btns-item" @click="handSee(f)">
					<div class="btn-icon">
					  <img :src="seeIcon" alt="查看" >
					</div>
					<span>查看</span>
				  </div>
				<div class="btns-item" v-if="!isDisable" @click="handDel(idx)">
					<div class="btn-icon">
					  <img :src="delIcon" alt="删除">
					</div>
					<span>删除</span>
				</div>
			</div>
          </div>
        </div>
      </div>
    </div>
  </div>

  <!-- 图片预览 -->
  <van-image-preview v-model:show="file.showViewer" :images="file.srcList" :startPosition="startPosition">
</van-image-preview>
  
  <!-- 视频弹框 -->
  <!-- 材料列表 -->
  <van-popup v-model:show="file.dialogVisible" position="right">
    <video :src="file.videoSrc" controls style="width: 100%; height: 100%;"></video>
  </van-popup>
</template>

<script setup>
import { ref, reactive, watch, watchEffect, computed } from 'vue'
import { useCustomFieldValue } from '@vant/use';
import icon from '@/assets/images/Frame.png';
import delIcon from '@/assets/images/del.png';
import seeIcon from '@/assets/images/see.png';
import imgIcon from '@/assets/images/img.png';
import wordIcon from '@/assets/images/word.png';
import pIcon from '@/assets/images/p.png';
import pdfIcon from '@/assets/images/pdf.png';
import exelIcon from '@/assets/images/exel.png';
import zipIcon from '@/assets/images/zip.png';
import otherIcon from '@/assets/images/other.png';
import { Toast } from 'vant';
import dsBridge from "dsbridge";

import Api from '@/api/file';
import { downloadFile, downFileChangeName } from '@/utils/request';
import { useFile } from '@/utils/useFile';
import { useRouter } from 'vue-router'
const router = useRouter()


let props = defineProps({
  tip: {
    type: String,
    default: ''
  },
  acceptType: {
    type: String,
    default: ''
  },
  multiple: {
    type: Boolean,
    default: false
  },
  capture: {
    type: String,
    default: ''
  },
  limit: {
    type: Number,
    default: 10
  },
  max: { // 文件上传大小
    type: Number,
    default: 2
  },
  fileList: { // 
    type: Array,
    default: () => []
  },
  isDisable: { // 附件上传
    type: Boolean,
    default: false
  },
  waterMaskConent: null // 水印内容
})
let emits = defineEmits(["change", "fileObj"])


// 图片
let imgType = ['png', 'jpg', 'jpeg', 'gif', 'bmp']
// 文档
let docType = [ 'doc', 'docx', 'xls', 'xlsx', 'pdf', 'ppt', 'pptx','txt']
// 下载
let downType = ['zip', 'rar']
// 视频
let videoType = ['mp4']

const setFileSize = (size) => {
  let kb = 1024;
  return `( ${(size / kb).toFixed(2)}KB )`
}
const setIcon = (file) => {
  let extension = ''
  if(!file.type) {
    const arr = file.name.split('.');
    extension = arr.pop();
    file.type = extension;
  } else {
    extension = file.type
  }
  
  if(imgType.includes(extension.toLowerCase())) {
    return imgIcon
  } else if (downType.includes(extension.toLowerCase())) {
    return zipIcon
  } else if (['doc', 'docx'].includes(extension.toLowerCase())) {
    return wordIcon
  } else if (['xls', 'xlsx'].includes(extension.toLowerCase())) {
    return exelIcon
  } else if (['pdf'].includes(extension.toLowerCase())) {
    return pdfIcon
  } else if (['ppt', 'pptx'].includes(extension.toLowerCase())) {
    return pIcon
  }
  else {
    return otherIcon
  }
}
// 文件对象
const file = reactive({
  list: [],
  srcList: [],
  showViewer: false,
  dialogVisible: false,
  videoSrc: '',
  isChange: true,
  fileObjList: []
})
useCustomFieldValue(()=>file.list.map(i => i.url))

// watch(() => props.fileList, (newV) => {
  
// })

const getFile = async(fileList) => {
  file.list = await useFile(fileList)
  file.fileObjList = file.list
  console.log(file.list)
}

watchEffect(() => {
  if(props.fileList.length) {
    console.log('侦听传入数据')
    if(!file.isChange) {
      return
    } 
    getFile(props.fileList)
  }
})

const fileRef = ref('')
const openFile = () => {
  fileRef.value.click()
}
const beforeUpload = (event) => {
  const fileList = event.target.files;
  if (props.limit != -1 && fileList.length + file.list.length > props.limit) {
    Toast('最多只能选择' + props.limit + '个文件');
    return false;
  }
  let tempList = file.list.map((item) => item.name);
  for (let i = 0; i < fileList.length; i++) {
    const file = fileList[i];
    if (file.size == 0) {
      Toast('文件内容为空，请重新选择');
      return false;
    }
    const fileMaxSize = 1024 * 1024 * props.max;
    if (file.size > fileMaxSize) {
      fileRef.value.value = null;
      Toast(`文件大小不能超过${props.max}M`);
      return;
    }

    if (!file) {
      fileRef.value.value = null;
      return;
    }
    const arrays = file.name.split('.');
    if (props.acceptType != '' && props.acceptType.indexOf(arrays[arrays.length - 1].toLowerCase()) < 0) {
      fileRef.value.value = null;
      Toast(`文件类型限制为${props.acceptType}`);
      return;
    }
    let count = 0;
    let fileName = file.name;
    while (count < tempList.length && tempList.includes(file.name)) {
      const inx = file.name.lastIndexOf('.');
      count = count + 1;
      if (inx > -1) {
        const beforeName = file.name.substring(0, inx);
        const typeName = file.name.substring(inx);
        fileName = beforeName + '(' + count + ')' + typeName;
      } else {
        fileName = file.name + '(' + count + ')';
      }
    }
    tempList.push(fileName);
    
    doUpload(file, fileName);
  }
  
}
const doUpload = async(file, fileName) => {
  file.isChange = false
  const toast = Toast.loading({
    message: '上传中...',
    forbidClick: true,
  	duration: 0
  });
  const formData = new FormData();
  formData.append('file', file, fileName);
  let res;
  try {
  if(!props.waterMaskConent) {
    res = await Api.upload(formData);
  } else {
    let types =['image/jpeg','image/png']
    if(types.includes(file.type)) {
      let contentList = props.waterMaskConent.contentList.filter(Boolean)
      formData.append('gysName', props.waterMaskConent.gysName);
      formData.append('contentList', JSON.stringify(contentList));
      formData.append('fontSize', 42);
      res = await Api.uploadWaterMask(formData);
    } else {
      res = await Api.upload(formData);
    }
    
    
  }
  }
  catch(error) {
    toast.close()
    fileRef.value.value = null
  }
  if(res && res.code == 200) {
      handleSuccess(res)
  } else {
    if(res && res.msg) Toast(res.msg);
  }
  toast.close()
  fileRef.value.value = null
}
const handleSuccess = (response) => {
  let { fileSize, url, name, id } = response.data;
  file.list.push({
    id,
    fileSize,
    url,
    name
  })

  file.fileObjList = file.list

  // 全文件
  emits('fileObj', file.fileObjList)
  // 处理上传链接
  emits('change', file.list.map(i => i.url))
}

const closeViewer = () => {
  file.showViewer = false
}

const handDown = (fileObj) => {
  if (dsBridge.hasNativeMethod("vueUpLoadFile")) {
      let res = dsBridge.call("vueUpLoadFile", fileObj.url);
  } else {
    if ("undefined" != typeof nativeMethod && nativeMethod?.vueUpLoadFile) {
      nativeMethod.vueUpLoadFile(fileObj.url);
      return false;
    }
    const a = document.createElement("a");
    a.download = fileObj.url?.match(/([^\/]+)$/g)[0];
    a.href = fileObj.url;
    a.click();
  }
  // const url = fileObj.url;
  // if(window.location.protocol == 'https:' && url.indexOf("http:") > -1){
  //   window.open(url)
  // } else if (url.indexOf('https:') > -1 || url.indexOf('http:') > -1) {
  //   downFileChangeName(url, fileObj.name)
  // } 
}
const startPosition = ref(0)
const handSee = (fileObj) => {
  if(imgType.includes(fileObj.type)) {
    file.srcList = file.list.filter(i => imgType.includes(i.type)).map(i => i.url)
	startPosition.value = file.srcList.findIndex(s => s == fileObj.url)
    file.showViewer = true
  }

  if (docType.includes(fileObj.type)) {
    let ssl = fileObj.url.indexOf('https') !== -1 ? 1 : 0;
    if (fileObj.url.indexOf('https') !== -1 || fileObj.url.indexOf('http') !== -1) {
		if (dsBridge.hasNativeMethod("vueOpenNewUrl")) {
			console.log('ios')
		   dsBridge.call("vueOpenNewUrl", { name: '文件预览', url: `https://wdyl.ddzg.cn:8089/?ssl=${ssl}&furl=${fileObj.url}`, flag: '' });
		} else if (
		  typeof window.nativeMethod !== "undefined" &&
		  window.nativeMethod &&
		  window.nativeMethod.vueOpenNewUrl
		) {
			console.log('andriod')
		 nativeMethod.vueOpenNewUrl(JSON.stringify({ name: '文件预览', url: `https://wdyl.ddzg.cn:8089/?ssl=${ssl}&furl=${fileObj.url}`, flag: '' }));
		} else {
			console.log('h5')
		  router.push({
			  path: '/webview',
			  query: {
				  src: `https://wdyl.ddzg.cn:8089/?ssl=${ssl}&furl=${fileObj.url}`
			  }
		  })
		}
    }
  }

  if(downType.includes(fileObj.type)) {
    if (fileObj.url.indexOf('https') !== -1 || fileObj.url.indexOf('http') !== -1) {
		if (dsBridge.hasNativeMethod("vueOpenNewUrl")) {
			console.log('ios')
		   dsBridge.call("vueOpenNewUrl", { name: '文件预览', url: fileObj.url, flag: '' });
		} if (
		  typeof window.nativeMethod !== "undefined" &&
		  window.nativeMethod &&
		  window.nativeMethod.vueOpenNewUrl
		) {
			console.log('android')
		 nativeMethod.vueOpenNewUrl(JSON.stringify({ name: '文件预览', url: fileObj.url, flag: '' }));
		} else {
			console.log('h5')
		  router.push({
			  path: '/webview',
			  query: {
				  src: fileObj.url
			  }
		  })
		}
    }
  }

  if(videoType.includes(fileObj.type)) {
    console.log(fileObj, '视频')
    file.dialogVisible = true
    file.videoSrc = fileObj.url
  }

  console.log(file.type)
}

const handDel = (index) => {
  file.isChange = false
  file.list.splice(index, 1)
  file.fileObjList = file.list
  emits('change', file.list.map(i => i.url))
  emits('fileObj', file.fileObjList)
}

const handleClose = () => {
  file.dialogVisible = false
}


</script>

<style lang="scss" scoped>
.list-btn {
  display: flex;
  align-items: center;
  font-size: 14px;
  .btn {
  display: flex;
  align-items: center;
  // padding: 5px 16px;
  justify-content: center;
  height: 28px;
  width: 98px;
  box-sizing: border-box;
  border-radius: 4px;
  border: 1px solid #436EE6;
  color: #436EE6;
  
  cursor: pointer;
  user-select: none;
  .icon {
    width: 16px;
    height: 16px;
    flex-shrink: 0;
    font-size: 14px;
    img {
      width: 100%;
      height: 100%;
    }
  }
  .text {
    padding-left: 8px;
    font-size: 14px;
  }
}

.tip {
  color: #606266;
  padding-left: 8px;
}
}
.upload-demo :deep(.el-upload-list) {
  display: none;
}

.list-warpper {
  display: flex;
  flex-direction: column;

}

.upload-list {
  .item {
    display: flex;
    // align-items: center;
    box-sizing: border-box;
    margin: 15px 0;
    
    .icon {
      width: 18px;
      height: 18px;
      user-select: none;
      margin-top: 3px;
      img {
        width: 100%;
        height: 100%;
      }
    }
    .name {
      color: #303133;
      font-size: 14px;
      padding: 0 6px;
      word-break: break-all;
    }
    .size {
      color: #C0C4CC;
      font-size: 12px;
      padding: 0 6px;
    }
    .btns {
      // flex: 1;
      display: flex;
      align-items: center;
      user-select: none;
      justify-content: flex-end;
      cursor: pointer;
	  
	  .btns-item{
	  	display: flex;
	  	align-items: center;
	  	font-size: 12px;
	  }
	  
      .btn-icon {
        font-size: 16px;
        margin-left: 8px;
		line-height: 16px;
		margin-right: 5px;
        img {
          width: 16px;
          height: 16px;
        }
      }
    }
  }
  .item:hover {
    background: #F5F7FA;
    border-radius: 4px;
  }
}

</style>